package service;

import org.xml.sax.SAXException;

import javax.xml.parsers.ParserConfigurationException;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created with IntelliJ IDEA.
 * User: Claudio "Dna" Bonesana
 * Date: 20.04.13
 * Time: 16:13
 */
public class ServiceUpdater extends Thread {

    private ServiceStatus serviceStatus;
    private int seconds;
    private Timer timer;

    public ServiceUpdater(ServiceStatus serviceStatus, int seconds) {
        this.serviceStatus = serviceStatus;
        this.seconds = seconds;
        this.serviceStatus.setUpdateTiming(seconds);
    }

    /**
     * Start the update task.
     */
    public void startTimer(){
        timer = new Timer();
        timer.schedule(new UpdateTask(), seconds * 1000);
    }

    /**
     * Update the current status every updateTime seconds.
     */
    class UpdateTask extends TimerTask{

        @Override
        public void run() {
            System.out.println("UPDATING: cities weather status.");

            try {
                serviceStatus.updateData();
            } catch (ParserConfigurationException e) {
                e.printStackTrace();
            } catch (SAXException e) {
                e.printStackTrace();
            }

            // Reload timer task.
            timer.schedule(new UpdateTask(), serviceStatus.getUpdateTiming() * 1000);
        }
    }
}
